package com.zyc.msmservice.controller;

import com.zyc.commonUtils.R;
import com.zyc.msmservice.service.MsmService;
import com.zyc.msmservice.utils.MsmUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author zyc
 * @create 2022-02-28-10:11
 */
@RestController
@RequestMapping("/edumsm")
@CrossOrigin //跨域
public class MsmApiController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping(value = "/send/{phone}")
    public R sendCode(@PathVariable String phone) {
        System.out.println(phone);
        String code = (String) redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            return R.ok();
        }

        code = MsmUtils.getFourRandom();
        HashMap<String, Object> map = new HashMap<>();
        map.put("code",code);
        boolean isSend = msmService.send(phone, "SMS_154950909", map);
        if (isSend) {
            redisTemplate.opsForValue().set(phone,Integer.valueOf(code),30, TimeUnit.MINUTES);
            return R.ok();
        } else {
            return R.error().message("验证码发送失败");
        }

    }
}
